<template>
  <el-dialog :visible="visible" title="用户编辑" @close="close">
    <el-form label-width="120px">
      <el-form-item label="部门名称">
        <el-input v-model="dept.name"></el-input>
      </el-form-item>

      <el-form-item :hidden="dept.id!==undefined" label="上级部门">

        <dept-tree ref="depttree" @change="chgdept"></dept-tree>

      </el-form-item>

      <el-form-item label="排序">
        <el-input-number v-model="dept.sorts" :min="1" label="排序"
                         style="margin-left: 20px;width: 60%"></el-input-number>
      </el-form-item>

      <el-form-item label="说明">
        <el-input v-model="dept.note" :rows="3" style="width:60%; margin-left : 20px" type="textarea"></el-input>
      </el-form-item>

      <div class="btn">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="info" @click="close">取消</el-button>
      </div>

    </el-form>
  </el-dialog>
</template>

<script>
// 导入部门树
const DeptTree = () => import("./DeptTree")
export default {
  data() {
    return {
      dept: {
        euid: "",
        name: "",
        note: "",
        pid: "1",
        sorts: 1
      }
    }
  },
  components: {
    DeptTree
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },

  methods: {
    chgdept($event) {
      this.dept.pid = $event.id
    },
    //显示当前dialog时调用的初始化方法
    init(data, parentDept) {
      const tmp = this.$session.getUser()
      if (data === undefined) {
        //说明是新增
        this.dept = {
          euid: tmp.euid,
          name: "",
          note: "",
          pid: parentDept.id || '1',
          sorts: 1
        };
      } else {
        //说明是修改
        this.dept = data
      }
      this.$nextTick(function () {
        this.$refs.depttree.init(parentDept)
      })
    },

    close() {
      this.$emit("update:visible", false)
    },
    save() {
      let promise;
      if (this.dept.id) {
        //如果用户id存在 说明是修改
        promise = this.$api.updateDept(this.dept)
      } else {
        promise = this.$api.saveDept(this.dept)
      }

      //处理结果
      promise.then(res => {
        if (res.code === 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          });
          this.close();
          //刷新数据
          this.$emit("refreshData")
        }
      })
    }
  }
}
</script>

<style scoped>
.btn {
  text-align: center;
  margin-top: 30px;
}

.btn button {
  margin-left: 50px;
}

.el-input {
  width: 60%;
  margin-left: 20px;
}

.pwd {
  color: #999;
  font-size: 14px;
  margin-left: 10px;
}
</style>
